<template>
	<view>
		<view class="top">
			<image class="bcg" src="https://www.daolangtongge.com/read-book-api/profile/mini_app/img/cbcg.png" mode=""></image>
			<view :class="navbar.isshowtabbar ? 'navbarbcg' : ''" class="navbar" :style="{ paddingTop: top + 'px' }">
				<view class="navbar_c" :style="{ width: `calc(100% - ${rightIcon}px)` }">
					<view class="navbar_l flex_jc_sb"></view>
					<view class="navbar_r flex_jc_cent" @click="$pageGo('/pages/community/searchCommunity')">
						<image src="/static/search.png" mode=""></image>
					</view>
				</view>
			</view>
			<view class="top_ads">
				<view class="img">
					<image src="/static/cc2.png" mode=""></image>
				</view>
				<view class="top_ads_cont flex_jc_sb">
					<view class="left">
						<image class="img1" src="/static/cleft.png" mode=""></image>
						<view class="left_ads flex">
							<image class="img2" src="/static/cc1.png" mode=""></image>
							<view class="rr">
								<view class="">畅所欲言</view>
								<view class="text_flex" >
									<view class="avatar-stack">
										<view v-for="(item, index) in dataInfo.headList" :key="index" class="avatar-item" :style="{ left: `${index * 20}rpx` }">
											<image v-if="item" :src="item" mode="aspectFill" :lazy-load="true"></image>
											<image v-else src="https://www.daolangtongge.com/read-book-api/profile/mini_app/img/head.png" mode="aspectFill" :lazy-load="true"></image>
										</view>
									</view>
									<view class="tests">{{ dataInfo.count }}人都在说...</view>
								</view>
							</view>
						</view>
					</view>

					<view class="right" @click="goRelease">
						<image src="/static/cright.png" mode=""></image>
						<view class="right_ads flex_jc_cent">说点什么...</view>
					</view>
				</view>
			</view>
		</view>
		<loadstatusVue :status="data.loadStatus">
			<view class="content">
				<view class="take_item" @click="goInfo(item)" v-for="(item, index) in data.list" :key="index">
					<view class="take_user flex_jc_sb">
						<view class="u_l flex">
							<image v-if="item.createUser.img" :src="item.createUser.img" mode="aspectFill"></image>
							<image v-else src="https://www.daolangtongge.com/read-book-api/profile/mini_app/img/head.png" mode=""></image>
							<view class="flex_r">
								<view class="t1">{{ item.createUser.name }}</view>
								<view class="t2">{{ item.createTime }}</view>
							</view>
						</view>
						<view class="u_r flex_jc_cent" v-if="item.top == 1">
							<view class="flex">
								<image src="/static/tt.png" mode=""></image>
								<view class="">已置顶</view>
							</view>
						</view>
					</view>
					<view class="texts">
						<view class="title">{{ item.title }}</view>
						<view class="t_content">
							{{ item.content }}
						</view>
					</view>
					<view class="imglist" v-if="item.images.length != 0">
						<view class="img_item" v-for="(img, ind) in item.images.slice(0, 4)" :key="ind">
							<image :src="img" mode="aspectFill"></image>
							<view class="item_ads flex_jc_cent" v-if="ind == 3 && item.images.length > 4">{{ item.images.length - 4 }} +</view>
						</view>
					</view>
					<view class="" v-if="item.lastReply">
						<view class="comment">
							<view class="ts">
								<text>{{ item.lastReply.user.name }}：</text>
								{{ item.lastReply.content }}
							</view>
							<view class="c_imglist" v-if="item.lastReply.images">
								<view class="img_item" v-for="(img, ind) in item.lastReply.images.split(',').slice(0, 4)" :key="ind">
									<image :src="img" mode="aspectFill"></image>
								</view>
							</view>
						</view>
					</view>
					<view class="hd" v-if="item.activity" @click.stop="$pageGo(`/pages/activity/info?id=${item.activityId}`)">
						<image src="/static/q.png" mode=""></image>
						{{item.activity.name}}
					</view>
					<view class="handle_block flex_jc_sb" @click.stop="">
						<view class="handle_l flex">
							<image src="/static/cc3.png" mode=""></image>
							<view class="input" @click="goInfo(item, 'input')">与人善言，暖于布帛</view>
						</view>
						<view class="handle_r flex">
							<image v-if="item.selfLike" src="/static/zan_1.png" mode="" @click="changeIMG(item, 1)"></image>
							<image v-else src="/static/zan.png" mode="" @click="changeIMG(item, 1)"></image>
							<image v-if="item.selfFlag" src="/static/xin_1.png" mode="" @click="changeIMG(item, 2)"></image>
							<image v-else src="/static/xin.png" mode="" @click="changeIMG(item, 2)"></image>
							<view class="">
								<image src="/static/zhuan.png" mode=""></image>
								<button class="zf_btns" open-type="share" :data-obj="item" ></button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</loadstatusVue>
		<view class="fixed_icon">
			<view class="fixed_img flex_jc_cent" v-if="navbar.isshowtabbar" @click="goRelease">
				<image src="/static/mb.png" mode=""></image>
			</view>
		</view>
		<uni-popup ref="popupRef" type="center">
			<view class="popup">
				<uni-icons @click="popupRef.close()" class="icon" type="closeempty" size="24" color="#AEAEAE"></uni-icons>
				<image src="/static/vip.png" mode=""></image>
				<view class="title">成为稻浪会员</view>
				<view class="pop_btn" @click="govip">加入稻浪同歌</view>
			</view>
		</uni-popup>
		<uv-tabbar :value="2" class="tab"></uv-tabbar>
	</view>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { onLoad, onShow, onReachBottom, onPageScroll,onPullDownRefresh,onHide,onShareAppMessage,onShareTimeline} from '@dcloudio/uni-app';
import loadstatusVue from '@/components/loadstatus/loadstatus.vue';
import { communityList, communityData, communityChangeLike } from '@/api/community.js';
import { toast } from '../../utils/common';
// 背景位置计算（单位统一为rpx）
const top = uni.getStorageSync('topIcon') || 0;
const rightIcon = uni.getStorageSync('rightIcon');
const data = reactive({
	list: [],
	loadStatus: 'before', // 加载状态
	hasMore: true, // 是否有更多数据
	isLoading: false, // 防止重复请求的锁
	queryParams: {
		pageNum: 1,
		pageSize: 5
	}
});
const navbar = reactive({
	scrollTop: 0,
	topImgHeight: 0,
	isshowtabbar: false
});
const scrollTop = ref(0);
const instance = getCurrentInstance();
const query = uni.createSelectorQuery().in(instance.proxy);
query
	.select('.top')
	.boundingClientRect((data) => {
		if (data) {
			navbar.topImgHeight = data.height - 60; // 存储高度（px）
		}
	})
	.exec();
onPageScroll((e) => {
	navbar.scrollTop = e.scrollTop;
	if (navbar.scrollTop >= navbar.topImgHeight) {
		navbar.isshowtabbar = true;
	} else {
		navbar.isshowtabbar = false;
	}
});

// 延迟函数
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// 设置加载状态的方法
const setLoadStatus = (status, options = {}) => {
	data.loadStatus = status;
};
// 处理响应数据的通用方法
const handleResponseData = async (res, isLoadMore = false) => {
	// 如果是加载更多，确保loading状态至少显示500ms，避免闪烁
	
	if (isLoadMore) {
		await delay(500);
	}
	if (res.code == 200) {
		uni.stopPullDownRefresh(); // 停止下拉刷新动画
		res.rows.forEach((item) => {
			if (item.images) {
				item.images = item.images.split(',');
			}
		});
		// 处理数据
		if (isLoadMore) {
			data.list.push(...res.rows);
		} else {
			data.list = res.rows || [];
		}
		// 判断是否有更多数据
		data.hasMore = res.rows && res.rows.length >= data.queryParams.pageSize;
		// 设置状态
		if (data.list.length === 0) {
			setLoadStatus('empty');
		} else if (!data.hasMore) {
			setLoadStatus('noMore');
		} else {
			setLoadStatus('success');
		}
		return true;
	}
	return false;
};
// 获取列表数据
const getList = async (isLoadMore = false) => {
	// 防止重复请求
	if (data.isLoading) return;
	try {
		data.isLoading = true;
		if (isLoadMore) {
			if (!data.hasMore) return;
			setLoadStatus('loading');
		} else {
			setLoadStatus('before');
			// 初始加载时显示loading至少1秒，避免闪烁
			await delay(500);
		}
		const res = await communityList(data.queryParams);
		const success = await handleResponseData(res, isLoadMore);
		if (!success) {
			// 请求失败的处理
			setLoadStatus(data.list.length === 0 ? 'empty' : 'success');
		}
	} catch (err) {
		await delay(500);
		setLoadStatus(data.list.length === 0 ? 'empty' : 'success');
	} finally {
		data.isLoading = false;
	}
};
const goInfo = (item, e) => {
	uni.navigateTo({
		url: `/pages/community/info?id=${item.id}&&type=${e}`
	});
};
const changeIMG = (item, type) => {
	communityChangeLike({ id: item.id, type: type }).then((res) => {
		if (res.code == 200) {
			if (type == 1) {
				toast(item.selfLike ? '取消点赞' : '已点赞');
				item.selfLike = !item.selfLike;
			} else {
				toast(item.selfFlag ? '取消收藏' : '已收藏');
				item.selfFlag = !item.selfFlag;
			}
		}
	});
};
// API 调用
import { getUser } from '@/api/user.js';
const userData = reactive({});
const getUserInfo = () => {
	getUser().then((res) => {
		if (res.code == 200) {
			Object.assign(userData, res.data.user);
		}
	});
};
const popupRef = ref(null)
const goRelease = () => {
	if (userData.vip == 0) {
		popupRef.value.open();
	} else {
		uni.navigateTo({
			url: '/pages/community/release'
		});
		popupRef.value.close();
	}
};
const govip = () => {
	uni.navigateTo({
		url: '/mypage/member/index'
	});
	popupRef.value.close();
};
const dataInfo = reactive({});
onPullDownRefresh(() => {
	data.queryParams.pageNum = 1
	getList()
});
onLoad(()=>{
	getList()
})
// onHide(()=>{
// 	uni.$off('changeCommunity')
// })
onShow(() => {
	getUserInfo()
	communityData({}).then((res) => {
		if (res.code == 200) {
			if (res.data.images) {
				res.data.images = res.data.images.split(',');
			}if(res.data.headList.length>3){
				res.data.headList = res.data.headList.splice(0,3);
			}
			Object.assign(dataInfo, res.data);
		}
	});
	uni.$on('changeCommunity',function(){
		data.queryParams.pageNum = 1
		getList()
	})
});

// 上拉加载更多
onReachBottom(() => {
	if (data.hasMore && (data.loadStatus === 'success' || data.loadStatus === 'noMore') && !data.isLoading) {
		data.queryParams.pageNum++;
		getList(true);
	}
});
onShareAppMessage((e) => {
	if (e.from === 'button') {
		let obj = e.target.dataset.obj;
		return {
			title: obj.title,
			imageUrl: obj.images[0] ? obj.images[0] : '',
			path: `pages/community/info?id=${obj.id}`
		};
	}
});
onShareTimeline((e) => {
	if (e.from === 'button') {
		let obj = e.target.dataset.obj;
		return {
			title: obj.title,
			imageUrl: obj.images[0] ? obj.images[0] : '',
			path: `pages/community/info?id=${obj.id}`
		};
	}
});
</script>

<style lang="scss">
page {
	background: #fbfcf9;
}
.popup {
	width: 620rpx;
	background: linear-gradient(180deg, #ece6d5 0%, #f7f8f6 100%);
	border-radius: 20rpx 20rpx 20rpx 20rpx;
	padding: 32rpx 30rpx;
	box-sizing: border-box;
	text-align: center;
	.icon {
		display: block;
		text-align: right;
	}
	image {
		width: 140rpx;
		height: 148rpx;
	}
	.title {
		font-family: PingFang SC, PingFang SC;
		font-weight: bold;
		font-size: 40rpx;
		color: #4e3f23;
		text-align: center;
		margin: 30rpx auto;
	}
	.pop_content {
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #b19561;
		text-align: center;
		margin: 40rpx auto;
	}
	.pop_btn {
		width: 280rpx;
		height: 72rpx;
		background: #d8c6a7;
		border-radius: 40rpx 40rpx 40rpx 40rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #75613e;
		text-align: center;
		line-height: 72rpx;
		margin: 0 auto;
	}
}
.fixed_icon {
	position: fixed;
	right: 20rpx;
	bottom: 160rpx;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
	.fixed_img {
		width: 100rpx;
		height: 100rpx;
		background: #d8c6a7;
		border-radius: 50rpx;
		border: 1px solid #75613e;
		image {
			width: 44rpx;
			height: 44rpx;
		}
	}
}

.top {
	height: 480rpx;
	position: relative;
	.bcg {
		width: 100%;
		height: 480rpx;
	}
	.navbar {
		width: 100%;
		top: 0%;
		position: fixed;
		z-index: 9;
	}
	.navbarbcg {
		background: #ece6d5;
	}
	.navbar_c {
		display: flex;
		justify-content: space-between;
		align-items: center;
		// height: 88rpx;
		padding: 0rpx 20rpx 0rpx 15rpx;
		box-sizing: border-box;
		.text {
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			color: #75613e;
		}
		.down {
			width: 24rpx;
			height: 18rpx;
			margin-left: 15rpx;
		}
		.navbar_r {
			width: 64rpx;
			height: 64rpx;
			background: rgba(0, 0, 0, 0.15);
			border-radius: 32rpx;
			image {
				width: 32rpx;
				height: 32rpx;
			}
		}
	}
	.top_ads {
		position: absolute;
		bottom: 94rpx;
		left: 20rpx;
		right: 20rpx;
		.img {
			width: 168rpx;
			height: 64rpx;
			margin-bottom: 30rpx;
			image {
				width: 168rpx;
				height: 64rpx;
			}
		}
		.top_ads_cont {
			.left {
				width: 460rpx;
				height: 98rpx;
				position: relative;
				.img1 {
					width: 460rpx;
					height: 98rpx;
				}
				.img2 {
					width: 88rpx;
					height: 60rpx;
				}
				.left_ads {
					width: 460rpx;
					height: 98rpx;
					position: absolute;
					top: 0%;
					padding: 0rpx 18rpx;
					box-sizing: border-box;
					.rr {
						margin-left: 8rpx;
						font-family: PingFang SC, PingFang SC;
						font-weight: bold;
						font-size: 28rpx;
						color: #75613e;
						.text_flex {
							display: flex;
							align-items: center;
							margin-top: 6rpx;
							.tests {
								font-family: PingFang SC, PingFang SC;
								font-weight: 500;
								font-size: 20rpx;
								color: #8f8f8b;
								margin-left: 8rpx;
							}
						}
						.avatar-stack {
							width: 70rpx;
							position: relative;
							display: inline-block;
							padding-right: 12rpx; /* 预留右侧空间 */
							height: 40rpx; /* 头像高度 */
						}
						.avatar-item {
							position: absolute;
							width: 30rpx;
							height: 30rpx;
							border-radius: 50%; /* 圆形头像 */
							transition: transform 0.2s;
							top: 5rpx;
							image {
								width: 30rpx;
								height: 30rpx;
								border-radius: 50%; /* 圆形头像 */
								border: 1px solid #fff;
							}
						}
					}
				}
			}
			.right {
				width: 248rpx;
				height: 98rpx;
				position: relative;
				image {
					width: 248rpx;
					height: 98rpx;
				}
				.right_ads {
					width: 248rpx;
					height: 98rpx;
					position: absolute;
					top: 0;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 32rpx;
					color: #75613e;
				}
			}
		}
	}
}
.content {
	width: 100%;
	margin: -95rpx auto 20rpx;
	position: relative;
	padding: 0rpx 20rpx;
	box-sizing: border-box;
	.take_item {
		width: 100%;
		background: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		box-sizing: border-box;
		margin: 20rpx auto;
		.take_user {
			.u_l {
				image {
					width: 60rpx;
					height: 60rpx;
					border-radius: 30rpx;
				}
				.flex_r {
					margin-left: 14rpx;
					.t1 {
						font-family: PingFang SC, PingFang SC;
						font-weight: 500;
						font-size: 24rpx;
						color: #000000;
					}
					.t2 {
						font-family: PingFang SC, PingFang SC;
						font-weight: 500;
						font-size: 20rpx;
						color: #8f8f8b;
					}
				}
			}
			.u_r {
				width: 124rpx;
				height: 44rpx;
				background: #ffffff;
				border-radius: 22rpx;
				border: 1px solid #b19561;
				image {
					width: 24rpx;
					height: 24rpx;
					margin-right: 4rpx;
				}
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				color: #b19561;
			}
		}
		.texts {
			.title {
				font-family: PingFang SC, PingFang SC;
				font-weight: bold;
				font-size: 30rpx;
				color: #1b1b1b;
				margin-top: 20rpx;
			}
			.t_content {
				margin-top: 20rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #1b1b1b;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 4; //几行就填几
				-webkit-box-orient: vertical;
				white-space: pre-wrap;
			}
		}

		.imglist {
			margin: 20rpx auto;
			display: flex;
			.img_item {
				width: 156rpx;
				height: 156rpx;
				margin-right: 14rpx;
				position: relative;
				image {
					width: 156rpx;
					height: 156rpx;
					border-radius: 12rpx;
				}
			}
			.item_ads {
				width: 156rpx;
				height: 156rpx;
				position: absolute;
				top: 0%;
				font-family: PingFang SC, PingFang SC;
				font-weight: bold;
				font-size: 28rpx;
				color: #ffffff;
				background: rgba(0, 0, 0, 0.5);
				border-radius: 12rpx;
			}
		}
		.comment {
			width: 670rpx;
			margin-top: 20rpx;
			background: #f7f7f7;
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			padding: 18rpx 20rpx;
			box-sizing: border-box;
			.ts {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				color: #1b1b1b;
				text {
					color: #979797;
				}
			}
			.c_imglist {
				margin-top: 20rpx;
				display: flex;
				.img_item {
					width: 148rpx;
					height: 148rpx;
					margin-right: 12rpx;
					position: relative;
					image {
						width: 148rpx;
						height: 148rpx;
						border-radius: 12rpx;
					}
				}
				.item_ads {
					width: 148rpx;
					height: 148rpx;
					position: absolute;
					top: 0%;
					font-family: PingFang SC, PingFang SC;
					font-weight: bold;
					font-size: 28rpx;
					color: #ffffff;
					background: rgba(0, 0, 0, 0.5);
					border-radius: 12rpx;
				}
			}
		}

		.hd {
			margin-top: 20rpx;
			height: 52rpx;
			background: #eee8d8;
			border-radius: 80rpx 80rpx 80rpx 80rpx;
			padding: 0rpx 24rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			color: #75613e;
			display: inline-block;
			line-height: 52rpx;
			image {
				width: 28rpx;
				height: 28rpx;
				margin-right: 10rpx;
				vertical-align: middle;
			}
		}

		.handle_block {
			margin-top: 20rpx;
			image {
				width: 48rpx;
				height: 48rpx;
			}
			.handle_l {
				.input {
					margin-left: 16rpx;
					width: 284rpx;
					height: 48rpx;
					background: #f7f7f7;
					border-radius: 24rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #d1d1d6;
					line-height: 48rpx;
					text-align: center;
				}
			}
			.handle_r {
				position: relative;
				image {
					margin-left: 50rpx;
				}
				.zf_btns{
					position: absolute;
					width: 50rpx;
					height: 50rpx;
					right: 0%;
					top: 0%;	
					opacity: 0;
				}
			}
		}
	}
}
</style>
